package com.atguigu.gmall.payment.controller;


import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    AlipayService alipayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submit(@PathVariable Long orderId){
        return alipayService.submit(orderId);
    }

    //同步回调
    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }

    //异步通知
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String,String> paramsMap){
        try {
            boolean signVerified  = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key,AlipayConfig.charset,AlipayConfig.sign_type);
            if (signVerified ){
                String tradeStatus = paramsMap.get("trade_status");
                if (tradeStatus.equals("TRADE_SUCCESS")) {
                    paymentInfoService.paySuccess(paramsMap);
                    return "success";
                }else {
                    return "failure";
                }
            }else {
                return "failure";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "failure";
    }
}
